<template>
  <div class="createPost-container">
    <el-dialog title="查看" :visible.sync="dialogVisible" width="98%" top="20px" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
      <dynamicEdit v-if="postForm.businessTable==='bus_dynamic_center'" :infoid="postForm.businessId" :read-only="true" :timestamp="timestamp2" @dialogHide="dialogHide($event)" />
      <dataCenterEdit v-if="postForm.businessTable==='bus_data_center'" :infoid="postForm.businessId" :read-only="true" :timestamp="timestamp2" @dialogHide="dialogHide($event)" />
      <salaryEdit v-if="postForm.businessTable==='bus_salary'" :infoid="postForm.businessId" :read-only="true" :timestamp="timestamp2" @dialogHide="dialogHide($event)" />
      <performanceEdit v-if="postForm.businessTable==='bus_performance'" :infoid="postForm.businessId" :read-only="true" :timestamp="timestamp2" @dialogHide="dialogHide($event)" />
      <courseEdit v-if="postForm.businessTable==='bus_course'" :infoid="postForm.businessId" :read-only="true" :timestamp="timestamp2" @dialogHide="dialogHide($event)" />
    </el-dialog>
    <el-form v-if="!infoLoading" ref="postForm" :model="postForm" :rules="rules" class="form-container" label-width="100px">
      <div class="createPost-main-container">
        <el-row>
          <el-col v-if="!readOnly" :span="4">
            <b>请选择接收用户</b>
            <el-tabs v-model="selectUserMode" @tab-click="tabChange">
              <el-tab-pane label="按部门选择" name="selectUserByDept">
                <el-input
                  v-model="filterText"
                  placeholder="输入关键字进行过滤"
                  style="margin:10px 0"
                />
                <el-tree
                  ref="tree"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  :data="treedata"
                  :filter-node-method="filterNode"
                />
              </el-tab-pane>
              <el-tab-pane label="按标签组选择" name="selectUserByGroup">
                <el-input
                  v-model="filterText2"
                  placeholder="输入关键字进行过滤"
                  style="margin:10px 0"
                />
                <el-tree
                  ref="tree2"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  :data="treedata2"
                  :filter-node-method="filterNode2"
                />
              </el-tab-pane>
            </el-tabs>
          </el-col>
          <el-col :span="20">
            <el-row>
              <el-col :span="24">
                <el-form-item label="来源">
                  <el-radio-group v-if="!readOnly" v-model="postForm.businessTable" @change="changeTable">
                    <el-radio-button label="" border>新建消息</el-radio-button>
                    <el-radio-button label="bus_dynamic_center" border>要闻速递</el-radio-button>
                    <el-radio-button label="bus_data_center" border>专题课程</el-radio-button>
                  </el-radio-group>
                  <template v-else>
                    {{ !postForm.businessTable||postForm.businessTable===''?'新建消息':'' }}
                    {{ postForm.businessTable==='bus_dynamic_center'?'要闻速递':'' }}
                    {{ postForm.businessTable==='bus_data_center'?'专题课程':'' }}
                    {{ postForm.businessTable==='bus_salary'?'工资单':'' }}
                    {{ postForm.businessTable==='bus_performance'?'绩效考核':'' }}
                    {{ postForm.businessTable==='bus_course'?'课程':'' }}

                  </template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item v-show="!readOnly" style="margin-bottom: 40px;" prop="title">
                  <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                    标题
                  </MDinput>
                </el-form-item>
                <el-form-item v-show="readOnly" label="标题">{{ postForm.title }}</el-form-item>
              </el-col>
            </el-row>
            <template v-if="!readOnly">
              <dynamicList v-if="postForm.businessTable==='bus_dynamic_center'" :is-edit="false" :is-selection="true" @selected="selected" />
              <dataCenterList v-if="postForm.businessTable==='bus_data_center'" :is-edit="false" :is-selection="true" @selected="selected" />
              <el-form-item v-if="postForm.businessTable===''" prop="content" style="margin-bottom: 30px;">
                <Tinymce ref="editor" v-model="postForm.content" :height="400" />
              </el-form-item>
              <div v-else style="margin:20px">
                <div v-if="selectedId">
                  您已选择{{ postForm.businessTable==='bus_dynamic_center'?'要闻速递':'' }}{{ postForm.businessTable==='bus_data_center'?'专题课程':'' }} ID：{{ selectedId }} 作为来源
                </div>
                <div v-else>您还未选择来源</div>
              </div>
            </template>
            <template v-else>
              <el-form-item v-if="!postForm.businessTable||postForm.businessTable===''" label="内容" style="margin-bottom: 30px;">
                <div v-html="postForm.content" />
              </el-form-item>
              <el-form-item v-else label="内容" style="margin-bottom: 30px;">
                <template>
                  您已选择{{ postForm.businessTable==='bus_dynamic_center'?' 要闻速递 ':'' }}{{ postForm.businessTable==='bus_data_center'?' 专题课程 ':'' }}{{ postForm.businessTable==='bus_salary'?' 工资单 ':'' }}{{ postForm.businessTable==='bus_performance'?' 绩效考核 ':'' }}{{ postForm.businessTable==='bus_examination'?' 考试 ':'' }}{{ postForm.businessTable==='bus_course'?' 课程 ':'' }} ID：{{ postForm.businessId }} 作为来源
                  <el-button v-if="postForm.businessTable!=='bus_salary'&&postForm.businessTable!=='bus_course'&&postForm.businessTable!=='bus_examination'" @click="detail()">查看</el-button>
                </template>
              </el-form-item>
            </template>
            <!-- <el-form-item v-if="!readOnly" label="接收部门" class="postInfo-container-item" prop="deptIds">
              <el-select v-model="postForm.deptIds" multiple placeholder="请选择" style="width:1000px">
                <el-option v-for="(item,index) in deptOption" :key="item+index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item v-if="!readOnly" label="接收用户" class="postInfo-container-item" prop="userIds">
              <el-select v-model="postForm.userIds" placeholder="请选择" multiple style="width:1000px">
                <el-option-group v-for="(group,index) in userOption" :key="index" :label="group.label">
                  <el-option v-for="(item,subindex) in group.options" :key="subindex" :label="item.label" :value="item.value" />
                </el-option-group>
              </el-select>
            </el-form-item> -->
            <div v-if="readOnly" style="overflow:hidden;clear:both">
              <el-table v-loading="infoLoading" :data="postForm.readUsers" border fit highlight-current-row style="width: 50%;float:left">
                <el-table-column label="已读" prop="realName" min-width="100" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.realName?scope.row.realName:'该用户已删除' }}
                  </template>
                </el-table-column>
              </el-table>
              <el-table v-loading="infoLoading" :data="postForm.unreadUsers" border fit highlight-current-row style="width: 50%;float:left">
                <el-table-column label="未读" prop="realName" min-width="100" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.realName?scope.row.realName:'该用户已删除' }}
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-form-item v-if="!readOnly" style="margin-bottom: 30px;" label-width="100px">
              <el-button type="primary" :loading="loading" @click="submitForm">提交</el-button>
              <el-button type="primary" style="position:fixed;right:80px;top:35px;" :loading="loading" @click="submitForm">提交</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import MDinput from '@/components/MDinput'
import dynamicList from '@/views/topic/list.vue'
import dataCenterList from '@/views/datacenter/list.vue'
import dynamicEdit from '@/views/topic/edit.vue'
import dataCenterEdit from '@/views/datacenter/edit.vue'
import salaryEdit from '@/views/payroll/edit.vue'
import performanceEdit from '@/views/performance/edit.vue'
import courseEdit from '@/views/course/edit.vue'
const defaultForm = {
  businessId: null,
  businessTable: '',
  content: '', // 文章内容
  deptIds: [],
  userIds: [],
  id: null,
  state: 1,
  title: '' // 文章题目
}
export default {
  name: 'ArticleDetail',
  components: { Tinymce, MDinput, dynamicList, dataCenterList, dynamicEdit, dataCenterEdit, salaryEdit, performanceEdit, courseEdit },
  props: {
    readOnly: {
      type: Boolean,
      default: false
    },
    infoid: {
      type: Number,
      default: 0
    },
    timestamp: {
      type: Number,
      default: 0
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: '请将表单填写完整',
          type: 'error'
        })
        callback(new Error('必填项'))
      } else {
        callback()
      }
    }
    return {
      selectUserMode: 'selectUserByDept',
      filterText: '',
      filterText2: '',
      treedata: [],
      treedata2: [],
      timestamp2: 0,
      dialogVisible: false,
      myHeaders: {},
      imageUrl: '',
      infoLoading: false,
      postForm: Object.assign({}, defaultForm),
      loading: false,
      deptOption: [],
      userOption: [],
      rules: {
        title: [{ validator: validateRequire }]
      },
      tempRoute: {},
      selectedId: 0,
      infoType: 0
    }
  },
  watch: {
    timestamp: {
      handler(val, oldVal) {
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([0])
        }
        if (this.$refs.tree2) {
          this.$refs.tree2.setCheckedKeys([0])
        }
        console.log('val:' + val)
        this.getData(this.infoid)
      },
      immediate: true
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    filterText2(val) {
      this.$refs.tree2.filter(val)
    }
  },
  mounted() {
    this.myHeaders = {
      Authorization: 'Bearer ' + localStorage.getItem('token')
    }
    this.getDepts()
    this.getGroup()
    this.getUsers()
  },
  created() {
    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)
  },
  methods: {
    tabChange() {
      console.log('tabChange')
      this.$refs.tree.setCheckedKeys([0])
      this.$refs.tree2.setCheckedKeys([0])
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    filterNode2(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    detail() {
      this.dialogVisible = true
      this.timestamp2 = new Date().getTime()
    },
    getDepts() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/sysDept/queryPage', para)
        .then(response => {
          if (response.data.success === true) {
            this.deptOption = []
            for (const item of response.data.result.records) {
              this.deptOption.push({ label: item.deptName, value: item.id })
              this.userOption.push({ label: item.deptName, options: [] })
              this.treedata.push({ id: item.id + 10000, label: item.deptName, children: [] })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getGroup() {
      const para = {
        pageNum: 1,
        pageSize: 1000
      }
      this.$http
        .post('/api/busGroup/queryGroupByPage', para)
        .then(response => {
          if (response.data.success === true) {
            console.log('resultgroup')
            console.log(response.data.result.records)
            for (const item of response.data.result.records) {
              // 为了防止作为key的用户id重复，选择或取消时无法取消重复的id，将id前面增加标签组id_加以区分
              this.treedata2.push({ id: 'g_' + item.id, label: item.title, children: item.membersArray.map(it => ({ id: item.id + '_' + it.id, label: it.realName + '(' + it.deptName + ')' })) })
            }
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    getUsers() {
      const para = {
        pageNum: 1,
        pageSize: 10000
      }
      this.$http
        .post('/api/sysUser/queryUserPage', para)
        .then(response => {
          if (response.data.success === true) {
            for (const item of response.data.result.records) {
              if (item.deptName && item.deptName !== '') {
                const theDept = this.userOption.filter((p) => {
                  return p.label === item.deptName
                })
                console.log(theDept)
                theDept[0].options.push({ label: item.realName, value: item.id })
                const treeDept = this.treedata.find((p) => {
                  return p.label === item.deptName
                })
                if (item.sysRoleId !== 1) { treeDept.children.push({ label: item.realName, id: item.id }) }
              }
            }
            this.treedata = this.treedata.filter(item => item.children.length > 0)
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    changeTable() {
      this.selectedId = null
    },
    selected(data) {
      this.selectedId = data.id
      this.postForm.title = data.title
      this.imageUrl = data.coverImg
    },
    handleAvatarSuccess(res, file) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      console.log('test')
      if (res.success) {
        this.$message({
          message: '上传成功！',
          type: 'success'
        })
        this.imageUrl = res.result[0].id
        // this.fileList = []
        // this.files = []
      } else {
        this.$message({
          message: '上传失败:' + res.message,
          type: 'error'
        })
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG && !isPNG && !isGIF) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
        return false
      }
      if (!isLt20M) {
        this.$message.error('上传图片大小不能超过 20MB!')
        return false
      }
    },
    getData(id) {
      if (id) {
        this.infoLoading = true
        this.$http
          .get('/api/busMessage/getDetailById?&id=' + id)
          .then(response => {
            this.infoLoading = false
            if (response.data.success === true) {
              console.log(response.data)
              this.postForm = response.data.result
            } else {
              console.log('获取失败:' + response.data.message)
              this.$message({
                message: '获取失败:' + response.data.message,
                type: 'error'
              })
            }
          })
          .catch(error => {
            console.log(error)
            this.infoLoading = false
          })
      } else {
        this.$nextTick(() => {
          this.infoLoading = false
          this.postForm = Object.assign({}, defaultForm)
          // this.$refs.editor.setContent('')
          if (this.$refs.editor) {
            this.$refs.editor.setContent('')
          }
        })
      }
    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          if (this.selectedId || this.postForm.businessTable === '') {
            if (this.postForm.businessTable === '' && this.postForm.content === '') {
              this.$message({
                message: '新建消息必须填写消息内容',
                type: 'error'
              })
              return
            }
            let checkedUser = []
            if (this.selectUserMode === 'selectUserByDept') {
              checkedUser = this.$refs.tree.getCheckedKeys()
              if (!checkedUser || checkedUser.length === 0) {
                this.$message({
                  message: '至少选一个接收用户',
                  type: 'error'
                })
                return
              }
            } else if (this.selectUserMode === 'selectUserByGroup') {
              checkedUser = this.$refs.tree2.getCheckedKeys()
              if (!checkedUser || checkedUser.length === 0) {
                this.$message({
                  message: '至少选一个接收用户',
                  type: 'error'
                })
                return
              }
              // 先过滤掉id为g_开头的标签组节点，然后再把人员节点去掉_和_前面的标签组id
              checkedUser = checkedUser.filter(item => item.split('_')[0] !== 'g').map(item => item.split('_')[1])
            }
            checkedUser = [...new Set(checkedUser)]
            // if (this.postForm.userIds.length === 0 && this.postForm.deptIds.length === 0) {
            //   this.$message({
            //     message: '接收部门和接收用户至少选一个',
            //     type: 'error'
            //   })
            //   return
            // }
            // console.log(checkedUser.filter(item => item < 10000))
            const day = new Date()
            day.setTime(day.getTime())
            let para = {}
            if (this.postForm.businessTable && this.postForm.businessTable !== '') {
              para = {
                businessId: this.selectedId,
                businessTable: this.postForm.businessTable,
                publishTime: day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate()),
                state: 1,
                title: this.postForm.title,
                userIds: checkedUser.filter(item => item < 10000)
                // deptIds: this.postForm.deptIds
              }
            } else {
              para = {
                content: this.postForm.content,
                publishTime: day.getFullYear() + '-' + this.add0(day.getMonth() + 1) + '-' + this.add0(day.getDate()),
                state: 1,
                title: this.postForm.title,
                userIds: checkedUser.filter(item => item < 10000) // 过滤掉部门、标签组节点，只保留人员
                // deptIds: this.postForm.deptIds
              }
            }
            this.loading = true
            this.$http
              .post('/api/busMessage/save', para)
              .then(response => {
                this.loading = false
                if (response.data.success === true) {
                  this.postForm.status = 'published'
                  this.postForm = Object.assign({}, defaultForm)
                  this.$message({
                    message: '提交成功',
                    type: 'success'
                  })
                  this.$emit('dialogHide')
                } else {
                  console.log('提交失败:' + response.data.message)
                  this.$message({
                    message: '提交失败:' + response.data.message,
                    type: 'error'
                  })
                }
              })
              .catch(function(error) {
                console.log(error)
                this.loading = false
              })
          } else {
            this.$message({
              message: '请选取一条信息',
              type: 'error'
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    // padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
